from django.shortcuts import render
from django.http.response import HttpResponse
from django.http import JsonResponse
from rest_framework.authentication import TokenAuthentication

from .models import *

from django.contrib.auth.models import User
from rest_framework.authtoken.views import APIView,AuthTokenSerializer
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.decorators import api_view, permission_classes, authentication_classes


# Create your views here.
def home(request):
    # return HttpResponse("Welcome to the home page!")
    return render(request, 'cabinet/index.html')


# 用户登录
class Login(APIView):
    def post(self, request, *args, **kwargs):
        serializer = AuthTokenSerializer(data=request.data,context={'request': request})
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        token, created = Token.objects.get_or_create(user=user)
        return Response({
            'status':True,
            'token': token.key,
            'user_id': user.pk,
            'user_name':user.username,
        })


def Logout(request):
    return JsonResponse({'status':'Logged Out'})


# 用户注册
class Register(APIView):
    def post(self,request, *args, **kwargs):
        username = request.data.get('username')
        password = request.data.get('password')
        if User.objects.filter(username=username).exists():
            resp = {
                'status':False,
                'data':'用户名已被注册'
            }
        else:
            user = User.objects.create_user(username=username,password=password,email='',is_staff=False,is_superuser=False,is_active=False)
            token, created = Token.objects.get_or_create(user=user)
            resp = {
                'status':True,
                'token': token.key,
                'user_id': user.pk,
                'user_name': user.username,
            }
        return Response(resp)


@api_view(['POST'])
# @authentication_classes([TokenAuthentication])  # 开启后会全局认证
@permission_classes([IsAuthenticated])
def Apidata(APIView):
    hardware = SERVERS.objects.all()
    cabinet_name = CABINET.objects.all()
    d = []  # 存储最终返回数据
    cab = []  # 存储机柜名
    # 取机柜名
    for cab_name in cabinet_name:
        cab.append(cab_name.btitle)
    # 生成机柜中设备列表
    for cab_s in sorted(cab):
        dev_device = []
        dev = {"name": cab_s, "cabinet_high": 42, "devices": []}
        # 生成每个机柜json中的devices设备列表.
        for i in hardware:
            if cab_s == i.S_cab.btitle:
                # 如果IP地址为0.0.0.0则不显示
                ip = i.S_ip if i.S_ip != '0.0.0.0' else ''
                # 单个机柜json数据
                dev_device.append({'cab': i.S_cab.btitle,'name': i.S_name,'bottom': i.S_bottom,'top': i.S_top,'ip': ip,'state': i.S_state,'color': i.S_color,'des': i.S_des})
        dev['devices'] = dev_device
        d.append(dev)

    return JsonResponse(d, safe=False)
